package exampleQuestions;

import java.util.LinkedList;

public class PrintTreeAccordingToLevel {
	
	static class Node {

		public Node(int i) {
			this.val = i;
		}

		Node left, right;
		int val;
	}
	
	static class NodeLevel {
		public NodeLevel(int i, Node n) {
			this.level = i;
			this.node = n;
		}
		Node node;
		int level;
	}

	public static void main(String[] args) {
		
		Node n = new Node(7);
		Node n2 = new Node(4);
		Node n3 = new Node(3);
		Node n4 = new Node(10);
		Node n5 = new Node(4);
		Node n6 = new Node(2);

		n.left = n2;
		n.right = n3;
		n2.left = n6;
		n6.right = n5;
		n3.left = n4;
		
		printTree(n);

	}

	private static void printTree(Node n) {
		
		if (n == null) {
			return;
		}
		
		LinkedList<NodeLevel> queue = new LinkedList<NodeLevel>();
		queue.add(new NodeLevel(0, n));
		
		int currentLevel = 0;
		while (!queue.isEmpty()) {
			
			NodeLevel nodeLevel = queue.removeLast();
			if (currentLevel < nodeLevel.level) {
				currentLevel++;
				System.out.println();
			}
			
			Node node = nodeLevel.node;
			System.out.print(node.val + " ");
			
			if (node.left != null) {
				queue.addFirst(new NodeLevel(nodeLevel.level + 1, node.left));
			}
			
			if (node.right != null) {
				queue.addFirst(new NodeLevel(nodeLevel.level + 1, node.right));
			}
		}
	}

}
